package com.legal.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis配置类，用于创建和配置RedisTemplate对象
 * 该配置类在RedisTemplate类存在时才会生效
 */
@Configuration
@Slf4j
@ConditionalOnClass(RedisTemplate.class)
public class RedisConfiguration {

    /**
     * 创建并配置RedisTemplate对象
     * 该方法仅在容器中没有名为"redisTemplate"的Bean时才会执行
     *
     * @param redisConnectionFactory Redis连接工厂，用于创建Redis连接
     * @return 返回配置好的RedisTemplate对象
     */
    @ConditionalOnMissingBean(name = "redisTemplate") // 容器中没有时才创建
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        try {
            log.info("开始创建Redis模板对象...");

            // 初始化RedisTemplate
            RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(redisConnectionFactory);

            // 设置序列化器
            setSerializers(redisTemplate);

            // 初始化并检查是否成功
            redisTemplate.afterPropertiesSet(); // 确保所有属性正确设置
            log.info("Redis模板对象创建成功");

            return redisTemplate;
        } catch (Exception e) {
            log.error("Redis模板对象创建失败", e);
            throw new RuntimeException("Redis模板对象初始化失败", e); // 抛出自定义异常以便上层处理
        }
    }

    /**
     * 设置RedisTemplate的序列化器
     */
    private void setSerializers(RedisTemplate<String, String> redisTemplate) {
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(stringRedisSerializer);

        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(stringRedisSerializer);
    }
}

